//
//  SuperviseTaskVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/1/6.
//
// 【首页-检查监督】检查任务-待完成列表

import Foundation
import UIKit
import Popover

class SuperviseTaskVC: SubLevelViewController, PullToRefreshPresentable {
    let segmentedC = ScrollableSegmentedControl()
    let tableView = UITableView(frame: .zero, style: .plain)
    
    var datas: [SpRwbgModal?] = []
    
    var rwkssj: String?
    var rwjssj: String?
    
    var param: SpCommonParam = SpCommonParam()
    
    var pageNum: Int = 1
    var totalPage: Int64 = 0

    fileprivate var options: [PopoverOption] = [
        .type(.auto), .showBlackOverlay(false), .cornerRadius(6), .color(.white), .arrowSize(CGSize(width: 10, height: 5))
    ]
    fileprivate var popover: Popover!
    
    init(withDeptId deptId: Int64? = nil, deptName: String? = nil, rwkssj: String? = nil, rwjssj: String? = nil) {
        super.init(nibName: nil, bundle: nil)
        self.deptId = deptId
        self.deptName = deptName
        self.rwkssj = rwkssj
        self.rwjssj = rwjssj
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navBarStyle(.white)
        view.backgroundColor = .white
        title = "检查任务"
        navigationItem.rightBarButtonItems = [menuBar]
        
        NotificationCenter.default.addObserver(self, selector: #selector(needReload), name: NotiSupervise, object: nil)

        setupUI()

        setupPullToRefresh(on: tableView)
        pageNum = 1

        param = SpCommonParam(wddm: deptId, rwkssj: rwkssj, rwjssj: rwjssj, pageSize: PageSize)
        reloadData()
    }
    
    deinit {
        tableView.removeAllPullToRefresh()
    }
    
    func reloadAction() {
        pageNum = 1
        getTask()
    }
    
    func loadAction() {
        if pageNum >= totalPage {
            return
        }
        pageNum += 1
        getTask()
    }
    
    @objc func needReload() {
        pageNum = 1
        reloadData()
    }
    
    func reloadData() {
        API.getJcjdRwzs(withParam: SpCommonParam(wddm: param.wddm, rwkssj: param.rwkssj, rwjssj: param.rwjssj, rwlxmc: param.rwlxmc)) { responseModel in
            DispatchQueue.main.async {
               if let modal = responseModel.model {
                   self.segmentedC.updateSegment(withTitle: "待完成(\(modal.wwcs ?? 0))", at: 0)
                   self.segmentedC.updateSegment(withTitle: "已完成(\(modal.wcs ?? 0))", at: 1)
                }
            }
        }
        
        self.getTask()
    }
    
    
    func getTask() {
        param.pageNum = pageNum
        param.status = segmentedC.selectedSegmentIndex == 0 ? 0 : 1
        API.getJcjdRwbg(withParam: param) { responseModel in
            DispatchQueue.main.async {
                if self.pageNum > 1 && (responseModel.models == nil || responseModel.models?.count == 0) {
                    self.pageNum -= 1
                    return
                }
                if self.pageNum == 1 {
                    self.datas.removeAll()
                }
                self.totalPage = responseModel.totalPage
                self.datas.append(contentsOf: responseModel.models ?? [])
                self.tableView.tableShowEmpty(withDataCount: self.datas.count)
                self.tableView.reloadData()
            }
        }
    }
    
    @objc func segmentSelected(sender: ScrollableSegmentedControl) {
        pageNum = 1
        getTask()
    }
    
    @objc func menuTapped() {
        let startPoint = CGPoint(x: ScreenWidth - 30, y: view.safeAreaInsets.top)
        let popoverView = SupervisePopoverView(frame: CGRect(x: 0, y: 0, width: 96, height: 80))
        popoverView.firstBtn.addTarget(self, action: #selector(createTapped), for: .touchUpInside)
        popoverView.lastBtn.addTarget(self, action: #selector(searchTapped), for: .touchUpInside)
        popover = Popover(options: options, showHandler: nil, dismissHandler: nil)
        popover.layer.shadowOffset = CGSize(width: 0, height: 6)
        popover.layer.shadowOpacity = 0.08
        popover.layer.shadowColor = UIColor.black.cgColor
        popover.show(popoverView, point: startPoint)
    }

    @objc private func createTapped() {
        popover.dismiss()
        navigationController?.pushViewController(SuperviseCreateTypeVC(), animated: true)
    }
    
    @objc func searchTapped() {
        popover.dismiss()

        let searchVC = SuperviseSearchVC()
        searchVC.didSelectItemWith = { (item) -> () in
            self.param.rwkssj = item.rwkssj
            self.param.rwjssj = item.rwjssj
            self.param.rwlxmc = item.rwlxmc
            self.needReload()
        }
        navigationController?.pushViewController(searchVC, animated: true)
    }
    
    // MARK: - Setup
    
    func setupUI() {
        segmentedC.tintColor = .primary
        segmentedC.underlineSelected = true
        segmentedC.segmentContentColor = .black
        segmentedC.selectedSegmentContentColor = .primary
        segmentedC.backgroundColor = .bg
        segmentedC.addTarget(self, action: #selector(segmentSelected(sender:)), for: .valueChanged)
        let normalAttrs = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]
        let highlightAttrs =  [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]
        let selectAttrs = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]
        segmentedC.setTitleTextAttributes(normalAttrs, for: .normal)
        segmentedC.setTitleTextAttributes(highlightAttrs, for: .highlighted)
        segmentedC.setTitleTextAttributes(selectAttrs, for: .selected)
        view.addSubview(segmentedC)
        segmentedC.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.left.right.centerX.equalToSuperview()
            make.height.equalTo(48)
        }
        
        segmentedC.insertSegment(withTitle: "待完成", at: 0)
        segmentedC.insertSegment(withTitle: "已完成", at: 1)
        segmentedC.selectedSegmentIndex = 0
        
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .white
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(segmentedC.snp.bottom)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
    
    lazy var menuBar: UIBarButtonItem = {
        let btn = UIButton(type: .custom)
        btn.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
        btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0)
        btn.setImage(UIImage(named: "ic_menu"), for: .normal)
        btn.addTarget(self, action: #selector(menuTapped), for: .touchUpInside)
        let bar = UIBarButtonItem(customView: btn)
        return bar
    }()
}

extension SuperviseTaskVC: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = datas[indexPath.row]
        let ID : String = "SuperviseTaskCell"
            
        var cell = tableView.dequeueReusableCell(withIdentifier: ID)
        if cell == nil {
            cell = SuperviseTaskCell(style: .subtitle, reuseIdentifier: ID)
        }
        
        (cell as? SuperviseTaskCell)?.reload(withModal: data)
        return cell!
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 110
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = datas[indexPath.row]
        if segmentedC.selectedSegmentIndex == 0 {
            navigationController?.pushViewController(SuperviseTaskCheckVC(id: data?.id!, deptName: deptName, deptId: deptId), animated: true)
        } else {
            navigationController?.pushViewController(SuperviseTaskDetailVC(id: data?.id!), animated: true)
        }
    }
}
